<template>
  <el-dialog v-model="visible" title="修改推荐人" :close-on-click-modal="false">
    <div class="container" id="container">
      <TreeChart :json="treeData" @click-node="clickNode"/>
    </div>

    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="120px"
      @keyup.enter="onSubmit()"
    >
      <el-form-item label="用户ID" prop="userId">
        <el-input v-model="dataForm.userId" :disabled="true" placeholder="用户ID" />
      </el-form-item>
      <el-form-item label="用户账号" prop="nickName">
        <el-input v-model="dataForm.nickName" :disabled="true" placeholder="用户账号" />
      </el-form-item>
      <el-form-item label="用户姓名" prop="realName">
        <el-input v-model="dataForm.realName" :disabled="true" placeholder="用户姓名" />
      </el-form-item>

      <el-form-item label="当前推荐人ID" prop="higherLevelUid">
        <el-input
          v-model="dataForm.higherLevelUid"
          :disabled="true"
          placeholder="当前推荐人ID"
        />
      </el-form-item>

      <el-form-item label="当前推荐人账号" prop="higherLevelName">
        <el-input
          v-model="dataForm.higherLevelName"
          :disabled="true"
          placeholder="当前推荐人账号"
        />
      </el-form-item>

      <el-form-item label="查询类型" prop="queryType">
        <el-radio-group v-model="dataForm.queryType">
          <el-radio :label="0">按账号</el-radio>
          <el-radio :label="1">按姓名</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="搜索值" prop="queryKey">
        <el-input v-model="dataForm.queryKey" placeholder="搜索值">
          <template #append>
            <el-link type="primary" @click="queryUser">搜索</el-link>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="选择推荐人" prop="setHigherLevelUid">
        <el-select v-model="dataForm.setHigherLevelUid" placeholder="请选择"  @change="selectHigherLevelUid">
          <el-option
            v-for="item in dataForm.queryUserList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit()">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import TreeChart from "vue-tree-chart-3";

//const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL;
const emit = defineEmits(["refreshDataList"]);

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10, // 每页显示多少条
});

const dataForm = ref({
  userId: "",
  nickName: "",
  realName: "",

  higherLevelUid: "",
  higherLevelName: "",

  queryType: 0,
  queryKey: "",
  queryUserList: [],

  setHigherLevelUid: "",
});

const dataRule = {
  setHigherLevelUid: [{ required: true, message: "选择推荐人不能为空", trigger: "blur" }],
};
const visible = ref(false);
const dataFormRef = ref(null);
const init = (row) => {
  visible.value = true;
  //dataForm.value = Object.assign({}, row) || {};
  dataForm.value = row || {};
  dataForm.value.queryType = 0;

  nextTick(() => {
    //在 el-form 中的字段,调用resetFields方法后会将当前值,覆盖为第一次打开el-form时各字段的值
    //dataFormRef.value?.resetFields();
  });

  if (dataForm.value.sharedUid) {
    http({
      url: http.adornUrl(`/admin/user/info/${dataForm.value.sharedUid}`),
      method: "get",
      params: http.adornParams(),
    }).then(({ data }) => {
      dataForm.value.higherLevelName = data.nickName;
    });
  }

  if (dataForm.value.userId) {
    http({
      url: http.adornUrl(`/admin/user/getLowerLevelBySharedUid/${dataForm.value.userId}`),
      method: "get",
      params: http.adornParams(),
    }).then(({ data }) => {
      treeData.value = data[0];
    });
  }
};
defineExpose({ init });

const queryUser = Debounce(() => {
  http({
    url: http.adornUrl(`/admin/user/getUserListByNickNameOrRealName`),
    method: "get",
    params: http.adornParams({
      queryType: dataForm.value.queryType,
      queryKey: dataForm.value.queryKey,
    }),
  }).then(({ data }) => {
    dataForm.value.queryUserList = data;
  });
});

const onSubmit = Debounce(() => {
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (dataForm.value.higherLevelUid == dataForm.value.setHigherLevelUid) {
        ElMessage.error("推荐人未改变,无需提交!");
        return;
      }
      http({
        url: http.adornUrl("/admin/user"),
        method: "put",
        data: http.adornData({
          userId: dataForm.value.userId || undefined,
          sharedUid: dataForm.value.setHigherLevelUid,
        }),
      }).then(() => {
        ElMessage({
          message: "操作成功",
          type: "success",
          duration: 1500,
          onClose: () => {
            visible.value = false;
            emit("refreshDataList", page);
          },
        });
      });
    }
  });
});

const treeData = ref({
  name: "root",
  image_url: "https://static.refined-x.com/avat.jpg",
  class: ["rootNode"],
  children: [
    {
      name: "children1",
      image_url: "https://static.refined-x.com/avat1.jpg",
    },
    {
      name: "children2",
      image_url: "https://static.refined-x.com/avat2.jpg",
      children: [
        {
          name: "grandchild",
          image_url: "https://static.refined-x.com/avat.jpg",
        },
        {
          name: "grandchild2",
          image_url: "https://static.refined-x.com/avat1.jpg",
        },
        {
          name: "grandchild3",
          image_url: "https://static.refined-x.com/avat2.jpg",
        },
      ],
    },
    {
      name: "children3",
      image_url: "https://static.refined-x.com/avat.jpg",
    },
  ],
});


const selectHigherLevelUid = (uid) => {
  http({
    url: http.adornUrl(`/admin/user/getAllHigherLevelUser/${uid}`),
    method: "get",
    params: http.adornParams({}),
  })
    .then(({ data }) => {
      console.log(data);
      data.forEach(number => {
        if(dataForm.value.userId == number.id){
          ElMessage.error(`本次修改账号:${dataForm.value.nickName},上级已出现 账号:${number.nickName},不能设置推荐人!`)

          dataForm.value.setHigherLevelUid="";
        }
      });
    })
    .catch(function (err) {

    });
};
const clickNode = (node) =>{
  // 节点点击事件的处理函数
  console.log('Node clicked:', node);
  // 这里可以执行更多操作，例如导航、更新数据等
};
</script>

<style scoped lang="scss">
/*.el-dialog__body > table > tr > td {
  padding: 0px 0 35px 0;
}
.el-dialog__body .node .person[data-v-5649378e] {
  width: 7em;
}*/
.container {
  height: 461px;
}
.el-form {
  //position: relative;
  //top: -192px;
}
/*.rootNode {
  width: 100px;
}*/
</style>

<style scoped>
/** lang="scss" 时,>>> 不生效 */
.container >>> .person {
  width: 7em !important;
}
.container >>> td {
  padding: 0px 0 35px 0;
}
</style>
